﻿using System;
using UnityEngine;

namespace Visual
{
    public class Beater : MonoBehaviour
    {
        public static Action Beat;
        
        [SerializeField] private int bpm = 90;
        [SerializeField] private float steps = 1;

        private AudioSource _audioSource;
        
        private int _lastInterval;


        private void Awake()
        {
            _audioSource = GetComponent<AudioSource>();
        }

        private void Update()
        {
            float sampledTime = _audioSource.timeSamples / (
                _audioSource.clip.frequency * GetIntervalLength());
            CheckForNewInterval(sampledTime);
        }

        private float GetIntervalLength()
        {
            return 60f / bpm * steps;
        }

        private void CheckForNewInterval(float interval)
        {
            if (Mathf.FloorToInt(interval) != _lastInterval)
            {
                _lastInterval = Mathf.FloorToInt(interval);
                Beat?.Invoke();
            }
        }
    }
}